﻿using System;
using System.Collections.Generic;

namespace 自定义Linq方法
{
    public static class LinqExtension
    {
        /// <summary>
        /// 自定义Count实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static int MyCount<T>(this IEnumerable<T> items, Func<T, bool> func)
        {
            int count = 0;
            foreach (var item in items)
            {
                if (func(item))
                {
                    count++;
                }
            }
            return count;
        }

        /// <summary>
        /// 自定义Where实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> items, Func<T, bool> func)
        {
            foreach (var item in items)
            {
                if (func(item))
                {
                    yield return item;
                }
            }
        }

        /// <summary>
        /// 自定义Where实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static IEnumerable<T> MyWhere1<T>(this IEnumerable<T> items, Func<T, bool> func)
        {
            var result = new List<T>();
            foreach (var item in items)
            {
                if (func(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }

        /// <summary>
        /// 自定义Select实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static IEnumerable<T2> MySelect<T1, T2>(this IEnumerable<T1> items, Func<T1, T2> func)
        {
            foreach (var item in items)
            {
                yield return func(item);
            }
        }
    }
}
